package com.example.video.conf;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.video.entity.User;
import com.example.video.common.Result;
import com.example.video.controller.ScheduleController;
import com.example.video.mapper.UserMapper;
import com.example.video.util.laixiOperate.Operate;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;

import java.net.URISyntaxException;
import java.util.List;

@Component
@Slf4j
public class DBUserDetailsManager implements UserDetailsManager, UserDetailsPasswordService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private Operate laixiOperate;
    @Resource
    private ScheduleController scheduleController;
    @Override
    public void createUser(UserDetails userDetails) {
        log.info("createUser"+userDetails);
        User user = new User();
        user.setUserName(userDetails.getUsername());
        user.setUserPwd(userDetails.getPassword());
        user.setRole(userDetails.getAuthorities().toString());
        // TODO:修改权限判断
        List<User> users = userMapper.selectList(new QueryWrapper<User>()
                .eq("role",user.getRole())
        );
        if(users == null || users.size() == 0){
            Result<String> result = null;
            try {
                result = laixiOperate.createGroup(user.getRole());
            } catch (URISyntaxException | InterruptedException e) {
                log.info("DBUserDetailsManager -> createUser ->msg: 来喜服务连接失败！！");
                e.printStackTrace();
            }
            if(result.getCode() == 0){
                user.setGroupId(result.getData());
            }
            scheduleController.setSchedule("12","12",user.getRole());
        }else{
            user.setGroupId(users.get(0).getGroupId());
        }


        user.setEnabled(true);
        userMapper.insert(user);
    }
    /**
     * 更新用户信息。
     * 该方法用于根据用户名更新用户的密码和角色信息。首先，它通过用户名查询数据库中是否存在该用户。如果用户存在，
     * 则更新用户的密码和角色信息；如果用户不存在，则抛出UsernameNotFoundException异常。
     *
     * @param userdetails 包含待更新用户信息的UserDetails对象，包括用户名、密码和角色权限。
     * @throws UsernameNotFoundException 如果根据用户名未找到用户，则抛出此异常。
     * @author ayan
     */
    @Override
    public void updateUser(UserDetails userdetails) {
        // 创建查询条件，指定查询用户名与userdetails中的用户名相等的用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userdetails.getUsername());
        log.info("update"+userdetails);
        // 根据查询条件尝试获取已存在的用户信息
        User existingUser = userMapper.selectOne(queryWrapper);

        log.info("existingUser"+existingUser);
        // 如果用户存在
        if (existingUser != null) {
            // 更新用户的密码
            existingUser.setUserPwd(userdetails.getPassword());
            // 更新用户的角色信息，这里将权限转换为字符串形式保存
            // 处理权限转换
            existingUser.setRole(userdetails.getAuthorities().toString());

            // 通过ID更新用户信息
            userMapper.updateById(existingUser);
        } else {
            // 如果用户不存在，抛出异常
            throw new UsernameNotFoundException("User not found: " + userdetails.getUsername());
        }
    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }
    /**
     * 从数据库中获取用户信息
     * @author lzy
     * @param userName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userName);
        User user = userMapper.selectOne(queryWrapper);
        if (user==null)
        {
            throw new UsernameNotFoundException(userName);
        }else {

          /*  Collection<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(()->"USER_LIST");
            authorities.add(()->"USER_ADD");

            return new org.springframework.security.core.userdetails.User(
                    user.getUserName(),
                    user.getUserPwd(),
                    user.getEnabled(),
                    true,//用户账号是否过期
                    true,//用户凭证是否过期
                    true,//用户是否未被锁定
                    authorities//权限列表
            );*/
            return org.springframework.security.core.userdetails.User
                    .withUsername(user.getUserName())
                    .password(user.getUserPwd())
                    .disabled(!user.getEnabled())//用户是否禁用
                    .credentialsExpired(false)//用户凭证是否过期
                    .accountLocked(false)//用户是否被锁定
                    .roles(user.getRole())
                    .build();
        }
    }

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        return null;
    }
}